package linkedlist.other_2_sortEvenOddList;

public class SortOddEvenList {
    /**
     * 给定奇数位升序，偶数位降序的链表，将链表重新排列成升序链表
     *
     * 思路：
     *      将奇偶链表拆分，将偶数位置链表反转，最后合并两个有序链表
     *
     *      因为是引用类型，断开奇数位置链表，剩下的就是偶数位置链表了
     */
    public ListNode sortOddEvenList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode evenList = head.next;
        ListNode oddList = splitList(head);
        evenList = reverse(evenList);
        return mergeTwoLists(oddList, evenList);
    }
    public ListNode splitList(ListNode head) {
        ListNode odd = head;
        ListNode even = head.next;
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = null;
        return head;
    }
    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummyNode = new ListNode(-1);
        ListNode pre = dummyNode;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                pre.next = l1;
                l1 = l1.next;
            } else {
                pre.next = l2;
                l2 = l2.next;
            }
            pre = pre.next;
        }
        pre.next = l1 == null ? l2 : l1;
        return dummyNode.next;
    }

    public static void main(String[] args) {
        SortOddEvenList obj = new SortOddEvenList();
        ListNode head = new ListNode(1);
        head.next = new ListNode(8);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(6);
        head.next.next.next.next = new ListNode(5);
        ListNode node = obj.sortOddEvenList(head);
        System.out.println(node.val);
        System.out.println(node.next.val);
        System.out.println(node.next.next.val);
        System.out.println(node.next.next.next.val);
        System.out.println(node.next.next.next.next.val);
    }
}
